<template>
  <DynamicList
    ref="rusticAdminListTable"
    v-bind="rusticAdminListColumns"
    @load-data="setPage"
    @reset-data="onResetData"
  >
    <template #tableTop>
      <a-space class="flex-wrap" size="small">
        <a-button
          v-if="$auth('rustic-admin-add')"
          type="primary"
          @click="router.push('/rusticAdmin/rusticAdminEdit')"
        >
          <PlusOutlined />
          新增
        </a-button>
      </a-space>
    </template>
    <template #searchQuery>
      <div class="inline-flex items-center whitespace-nowrap">
        <span class="pr-8px">在本村的角色：</span>
        <a-select
          v-model:value="queryData.roleId"
          class="min-w-150px"
          allow-clear
          :options="formattedRoleOption"
          placeholder="请选择角色"
        ></a-select>
      </div>
      <div class="inline-flex items-center">
        <span class="pr-8px">创建时间：</span>
        <a-range-picker
          v-model:value="createTime"
          :format="valueFormat"
          show-time
          @change="(date, dateString) => onRangeChange('startDate', dateString)"
        />
      </div>
    </template>
  </DynamicList>
</template>

<script setup lang="tsx">
  import { ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons-vue';
  import { Avatar, message, Modal, Tag } from 'ant-design-vue';
  import type { Dayjs } from 'dayjs';
  import { deleteRusticAdmin, rusticAdminApi } from '@/api/rustic/rusticAdmin';
  import { formatToDateTime } from '@/utils/dateUtil';
  import DynamicList from '@/components/dynamicList/index.vue';
  import { RequestEnum } from '@/enums/httpEnum';
  import { publicPathUrl } from '@/utils/common';
  import useRequestList from '@/hooks/useRequestList';
  import { verifyAuth } from '@/core/permission';
  import { getFileHttpUrl } from '@/utils/urlUtils';
  import { ComponentsTypeEnum } from '@/enums/componentsEnum';
  import { useUserStore } from '@/store/modules/user';
  import { getRoleListJson } from '@/api/system/role';

  const valueFormat = 'YYYY-MM-DD HH:mm';
  type RangeValue = [Dayjs, Dayjs];
  const rusticAdminListTable = ref<any>(null);
  const roleOption = ref<Array<any>>([]);
  const router = useRouter();
  const userStore = useUserStore();
  const rusticId = userStore.getRusticId();
  const createTime = ref<RangeValue | string[]>();

  defineOptions({
    name: 'rusticAdminList',
  });

  interface QueryDataParams {
    endCreateTime: string;
    startCreateTime: string;
    rusticId: number;
    roleId: number | null;
  }
  const queryData = reactive<QueryDataParams>({
    endCreateTime: '',
    startCreateTime: '',
    // 填写进入的乡村id
    rusticId: userStore.getRusticId(),
    roleId: null,
  });

  const { list, page, setPage, loading, setParams } = useRequestList({
    apiKey: rusticAdminApi.rusticAdminList,
    type: RequestEnum.GET,
    initParam: {
      rusticId: queryData.rusticId,
    },
  });
  const rusticAdminListColumns = ref({
    columns: [
      {
        title: '序号',
        width: 50,
        align: 'center',
        dataIndex: 'index',
        fixed: 'left',
        customRender: ({ record, text, index }) => index + 1,
      },
      {
        title: '头像',
        width: 50,
        align: 'center',
        dataIndex: 'avatar',
        customRender: ({ text }) => {
          return text ? <a-image width="80px" src={getFileHttpUrl(text)} /> : '-';
        },
      },
      {
        title: '登录账号',
        width: 50,
        align: 'center',
        dataIndex: 'username',
        search: true,
        component: ComponentsTypeEnum.Input,
      },
      {
        title: '用户昵称',
        width: 50,
        align: 'center',
        dataIndex: 'nickname',
      },
      {
        title: '在本村的角色',
        width: 50,
        align: 'center',
        dataIndex: 'roleName',
      },
      {
        title: '手机号码',
        width: 50,
        align: 'center',
        dataIndex: 'mobile',
      },
      {
        title: '最后登录IP',
        width: 50,
        align: 'center',
        dataIndex: 'loginIp',
      },
      {
        title: '最后登录时间',
        width: 50,
        align: 'center',
        dataIndex: 'loginDate',
        customRender: ({ text }) => {
          return text ? formatToDateTime(text) : '-';
        },
      },

      {
        title: '创建时间',
        width: 50,
        align: 'center',
        dataIndex: 'createTime',
        customRender: ({ text }) => {
          return text ? formatToDateTime(text) : '-';
        },
      },
      {
        title: '操作',
        width: 150,
        dataIndex: 'operation',
        align: 'center',
        fixed: 'right',
        actions: [
          {
            title: '编辑',
            vIf: verifyAuth('rustic-admin-update'),
            onClick: (record) => {
              router.push(`/rusticAdmin/rusticAdminEdit?id=${record.id}`);
            },
          },
          {
            title: '删除',
            vIf: verifyAuth('rustic-admin-delete'),
            onClick: (record) => {
              deleteConfirmRusticAdmin(record);
            },
          },
        ],
      },
    ],
    pageParams: page,
    list,
    loading,
    columnProps: {
      bordered: true,
    },
    queryParamsSlots: queryData,
  });

  const deleteConfirmRusticAdmin = async (record) => {
    Modal.confirm({
      title: '确定要删除吗?',
      icon: <ExclamationCircleOutlined />,
      centered: true,
      onOk: async () => {
        const res = await deleteRusticAdmin({ adminId: record.id, rusticId });
        if (res) {
          message.success(res?.msg);
          rusticAdminListTable.value && rusticAdminListTable.value.resetFields();
        }
      },
    });
  };

  const getRoleList = async () => {
    const res = await getRoleListJson();
    if (res) {
      roleOption.value = res;
    } else {
      roleOption.value = [];
    }
  };
  // 使用computed属性来转换roleOption数组
  const formattedRoleOption = computed(() => {
    return roleOption.value.map((item) => ({
      label: item.roleName, // 显示在下拉列表中的文本
      value: item.id, // 选择后传递的值
    }));
  });

  const onRangeChange = (type: string, dateString: string[]) => {
    queryData.startCreateTime = dateString[0];
    queryData.endCreateTime = dateString[1];
  };
  const onResetData = (queryParams: Object) => {
    for (const queryParamsKey in queryData) {
      queryData[queryParamsKey] = null;
    }
    createTime.value = [queryData.startCreateTime, queryData.endCreateTime];
    setPage(queryParams);
  };
  onMounted(() => {
    getRoleList();
  });
</script>

<style></style>
